<template>
  <div class="tui-radio-container">
    <input
      type="radio"
      :id="id"
      :name="name"
      :value="value"
      :checked="modelValue === value"
      :disabled="disabled"
      :required="required"
      class="tui-radio"
      @change="handleChange"
      @focus="handleFocus"
      @blur="handleBlur"
    />
    <span class="tui-radio-text">{{ label }}</span>
    <p v-if="errorMessage" class="tui-radio-error">{{ errorMessage }}</p>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import type { PropType } from 'vue';

// 定义组件props
const props = defineProps({
  /**
   * 单选按钮的id
   */
  id: {
    type: String,
    default: '',
  },
  /**
   * 单选按钮组的name属性，同一组的单选按钮应具有相同的name
   */
  name: {
    type: String,
    default: '',
    required: true,
  },
  /**
   * 绑定的值
   */
  modelValue: {
    type: [String, Number, Boolean],
    default: '',
  },
  /**
   * 单选按钮的值
   */
  value: {
    type: [String, Number, Boolean],
    default: '',
    required: true,
 },
  /**
   * 单选按钮的标签文字
   */
  label: {
    type: String,
    default: '',
  },
  /**
   * 是否禁用
   */
  disabled: {
    type: Boolean,
    default: false,
  },
  /**
   * 是否必填
   */
  required: {
    type: Boolean,
    default: false,
  },
  /**
   * 错误信息
   */
  errorMessage: {
    type: String,
    default: '',
  },
});

// 定义emits
const emit = defineEmits<{
  (e: 'update:modelValue', value: string | number | boolean): void;
  (e: 'change', event: Event): void;
  (e: 'focus', event: FocusEvent): void;
  (e: 'blur', event: FocusEvent): void;
}>();

// 处理变化事件
const handleChange = (event: Event) => {
  emit('update:modelValue', props.value);
  emit('change', event);
};

// 处理聚焦事件
const handleFocus = (event: FocusEvent) => {
  emit('focus', event);
};

// 处理失焦事件
const handleBlur = (event: FocusEvent) => {
  emit('blur', event);
};
</script>

<style scoped>
.tui-radio-container {
  display: inline-flex;
  align-items: center;
  margin-right: 20px;
}

.tui-radio-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
}

.tui-radio {
  width: 16px;
  height: 16px;
  margin-right: 8px;
  accent-color: var(--tui-color-primary);
}

.tui-radio:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.tui-radio-text {
  font-size: 14px;
}

.tui-radio-error {
  color: var(--tui-color-danger);
  font-size: 12px;
  margin-top: 4px;
  margin-bottom: 0;
  margin-left: 24px;
}
</style>